package com.yutian.example.demo.common.utils;

import com.google.common.collect.Maps;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.Map;

/**

 * 项目名称:

 * 类名: SpringContextUtil

 * 描述： 获取bean的工具类，可用于在线程里面获取bean

 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    public static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);

    private static ApplicationContext context = null;

 

    /* (non Javadoc)

     * @Title: setApplicationContext

     * @Description: spring获取bean工具类

     * @param applicationContext

     * @throws BeansException

     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)

     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.context = applicationContext;
    }


    public static <T> T getBean(String beanName, Class<T> requiredType) {
        try {
            return (T) context.getBean(beanName, requiredType);
        } catch (BeansException e) {
            return null;
        }
    }

    public static <T> Map<String, T> getBean(Class<T> requiredType) {
        Map<String, T> result = Maps.newHashMap();
        try {
            result = context.getBeansOfType(requiredType);
        } catch (BeansException e) {
            return result;
        }
        return result;
    }
 

    // 国际化使用
    public static String getMessage(String key) {
        return getMessage(key, null);
    }

    // 国际化使用
    public static String getMessage(String key, Object[] args) {
        return context.getMessage(key, args, key, Locale.getDefault());
    }

    /**
     * 一个Environment中默认会包含两个PropertySource，分别对应于系统属性和环境变量。即默认情况下在只有系统属性和环境变量对应的两个ProperySource时，如果我们从Environment中获取某属性，将先从系统属性中取，没取到再从环境变量中获取。
     * 注：springboot中似乎Environment自动加载了application.propreties，而rose中没有！
     * @param propertykey
     * @param defaultVal
     * @return
     */
    public static String getEnvironment(String propertykey, String defaultVal) {
        return context.getEnvironment().getProperty(propertykey, defaultVal);
    }

}